package logic

import (
	"api/pkg"
	"context"
	"fmt"
	"user_srv/user"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendSmsCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsCodeLogic {
	return &SendSmsCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendSmsCodeLogic) SendSmsCode(req *types.SendSmsCodeRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 短信发送

	if !pkg.MobileType(req.Mobile) {

		return &types.RegMsgResponse{
			Code: -2,
			Msg:  "手机号格式错误",
			Data: nil,
		}, err
	}

	//生成短信验证码
	code := pkg.NumSmsCode()
	fmt.Println("短信验证码是....", code)

	err = pkg.SendSmsCode(req.Mobile, code)
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "短信发送失败",
			Data: nil,
		}, err
	}

	_, err = l.svcCtx.UserSrv.SendSmsCode(l.ctx, &user.SendSmsCodeRequest{
		Mobile: req.Mobile,
		Code:   code,
		Sale:   req.Sale,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Code: 0,
		Msg:  "短信发送成功",
		Data: nil,
	}, err
}
